/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package me.joshua.tools4j.web;

import java.util.List;

import me.joshua.tools4j.dal.CheckPointRepository;
import me.joshua.tools4j.dal.SubscriptionRepository;
import me.joshua.tools4j.model.CheckPoint;
import me.joshua.tools4j.model.Subscription;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * 
 * @author Joshua
 */
@Controller
@RequestMapping("/subscription/checkpoint")
public class CheckPointController {

	@Autowired
	private CheckPointRepository	checkPointRepository;
	@Autowired
	private SubscriptionRepository	subscriptionRepository;

	@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
	public @ResponseBody
	CheckPoint get(@PathVariable("id") CheckPoint point) {
		return point;
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(Model model) {
		model.addAttribute("isNew", true);
		CheckPoint point = new CheckPoint();
		return edit(point, model);
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@PathVariable("id") CheckPoint point, Model model) {
		model.addAttribute("point", point);
		List<Subscription> subscriptions = subscriptionRepository.findByEnabled(true);
		model.addAttribute("subscriptions", subscriptions);
		return "/page/subscription/checkpoint/edit";
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public String edit(CheckPoint point) {
		checkPointRepository.save(point);
		return "redirect:" + UriComponentsBuilder.fromPath("/subscription/checkpoint/edit/{id}").buildAndExpand(point.getId());
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		List<CheckPoint> points = checkPointRepository.findByEnabled(true);
		model.addAttribute("points", points);
		return "/page/subscription/checkpoint/list";
	}

	@RequestMapping(value = "/del/{id}", method = RequestMethod.GET)
	public @ResponseBody
	CheckPoint del(@PathVariable("id") CheckPoint point) {
		if (null == point) {
			return null;
		}
		checkPointRepository.delete(point);
		return point;
	}

}
